# -*- coding: utf-8 -*-
from env import *
import os,sys,re
import pyvisa as visa
import logging
class USBDevice(object):
    def __init__(self, device_name=None, log=None):
        self.__rm = visa.ResourceManager()
        self._device = None
        self.log = log
        self.logFlag = True
        if device_name:
            device_list = self.list_device()
            for index in range(len(device_list)):
                if device_list[index] == device_name:
                    if self.connect(device_name):
                        self.write_log('Connected to USB ID {}'.format(device_name))
                        break
                    else:
                        exit()
            else:
                self.write_error_log("Can't find the device:" + device_name)
                logging.error("Can't find the device:" + device_name)
                exit()
        else:
            pass

    def __del__(self):
        if self._device:
            self._device.close()

    @classmethod
    def list_device(cls):
        return visa.ResourceManager().list_resources()

    def connect(self, device_name):
        ren = True
        try:
            self._device = self.__rm.open_resource(device_name)
            self._device.clear()#20230803byangel:避免传输打断引起下一次问询异常
            self._device.chunk_size = 20*1024*1024#20230803byangel:default is 20*1024
            # self._device.read_termination = "\n"#20230728byangel:usbtmc通信时需屏蔽此行，否则会截断
        except:
            self.write_error_log("Fail to open the device:" + device_name)
            logging.error("Fail to open the device:" + device_name)
            ren = False
        return ren

    def remove(self):
        self._device.close()

    def lock(self):
        self._device.lock_excl()

    def unlock(self):
        self._device.unlock()

    def write(self, command):
        #if self.logFlag::
        self.write_log('SEND >  ' + str(command))
        self._device.write(command)

    def read(self):
        response = self._device.read()
        #if self.logFlag::
        self.write_log('RECV >  ' + str(response))
        return response

    def query(self, command, delay=None):
        """VISA 通信接口查询命令"""
        self.write_log('SEND >  ' + str(command))
        response = self._device.query(command, delay)
        self.write_log('RECV >  ' + str(response))
        return response

    def write_raw(self, command):
        return self._device.write_raw(command)

    def read_raw(self, size=None):
        return self._device.read_raw(size)

    def set_timeout(self, value=2000):
        self._device.timeout = value

    def get_timeout(self):
        return self._device.timeout

    def write_log(self, message):
        if not self.log or not self.logFlag:
            return
        if len(message) > 500:
            self.log.write(len(message))
        else:
            self.log.write(message)

    def write_error_log(self, message):
        if not self.log or not self.logFlag:
            return
        self.log.writeError(message)
